<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <title>定位</title>
  <!-- 引入高德地图 JS API，并显式加载 Geolocation 插件 -->
  <script
    src="https://webapi.amap.com/maps?v=2.0&key=c9c069d05cb4075e3e24aefea6f77b85&plugin=AMap.Geolocation"
    crossorigin="anonymous"
    defer></script>
</head>

<body>
  <!-- 引入 uni.webview.js -->
  <script src="./js/uni.webview.1.5.6.js"></script>
  <script>
    let pos = '';

    // 浏览器定位
    function locate () {
      console.log('window.locate');

      // 调用高德定位
      useAMapGeolocation();
    }

    // 使用高德定位
    function useAMapGeolocation () {
      // 动态加载 Geolocation 插件
      AMap.plugin('AMap.Geolocation', () => {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          zoomToAccuracy: true,
          needAddress: true,
          showButton: false,
        });

        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            const offsetLng = result.position.lng + 0.005536;
            const offsetLat = result.position.lat - 0.001329;
            pos = [offsetLng, offsetLat];
            // console.log('高德定位成功:', pos);
            // 直接发送 pos 数据
            window.parent.postMessage({
              type: 'locationUpdate',
              params: JSON.stringify(pos)
            }, '*');
          } else {
            console.error('高德定位失败:', result);
            alert('无法获取您的位置信息，请检查网络或权限设置。');
          }
        });
      });
    }

    window.addEventListener('message', function (event) {
      if (event.data.type === 'forceRelocate') {
        locate();
      }
    });

    // 获取实时定位
    let count = 0;
    const intervalId = setInterval(() => {
      locate();
      count++;
      if (count >= 1) {
        clearInterval(intervalId);  // 停止定时器
      }
    }, 1000);
  </script>
</body>

</html>